import pymysql


# 创建数据库 工具类 用大驼峰
class DBTools(object):

    # 创建 工具方法 创建连接
    @staticmethod
    def __create_conn():
        conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2022",
                               database="ihrm", charset="utf8")
        return conn

    # 创建 查询方法 查一条
    @staticmethod
    def query_one(sql):
        my_conn = None
        my_cursor = None
        res = None
        try:
            my_conn = DBTools.__create_conn()
            my_cursor = my_conn.cursor()
            my_cursor.execute(sql)
            # 提取一条记录
            res = my_cursor.fetchone()
        except Exception as err:
            print("执行查询sql错误", str(err))
        finally:
            my_cursor.close()
            my_conn.close()
            return res

    # 创建 增删改方法
    @staticmethod
    def db_idu(sql):
        my_conn = None
        my_cursor = None
        try:
            my_conn = DBTools.__create_conn()
            my_cursor = my_conn.cursor()
            my_cursor.execute(sql)
            print("Affected rows：", my_conn.affected_rows())
            my_conn.commit()  # 提交事务
        except Exception as err:
            print("执行增删改sql错误", str(err))
            my_conn.rollback()
        finally:
            my_cursor.close()
            my_conn.close()


if __name__ == '__main__':
    result = DBTools.query_one("select * from t_hero;")
    print(result)
